package main

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/nanakura/decumbersome-tool/model"
	"gitee.com/nanakura/decumbersome-tool/utils"
	"golang.org/x/exp/slog"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// GetTemplateList 获取模板文件夹内模板列表
func (a *App) GetTemplateList() []string {
	var res []string
	templateDirPath, err := utils.SplicePath([]string{"templates"})
	if err != nil {
		slog.Error("error occur", err)
		return res
	}
	err = filepath.Walk(templateDirPath, func(path string, info fs.FileInfo, err error) error {
		if !info.IsDir() {
			res = append(res, info.Name())
		}
		return nil
	})
	if err != nil {
		slog.Error("error occur", err)
		return nil
	}
	return res
}

// GetTemplateContent 获取模板内容
func (a *App) GetTemplateContent(filename string) string {
	var res string
	filePath, err := utils.SplicePath([]string{"templates", filename})
	if err != nil {
		slog.Error("error occur", err)
		return res
	}
	slog.Info("get template pth", "path", filePath)
	iot, err := os.ReadFile(filePath)
	if err != nil {
		slog.Error("error occur", err)
		return res
	}
	res = string(iot)
	return res
}

// GetOptionsByTemplateName get template's options
func (a *App) GetOptionsByTemplateName(name string) (res []string) {
	rawStruct := new(model.TemplateOptionsModel)
	splitsRes := strings.Split(name, ".")
	filename := fmt.Sprintf("%s.json", splitsRes[0])
	filePath, err := utils.SplicePath([]string{"opts", filename})
	if err != nil {
		slog.Error("error occur", err)
		return res
	}
	bytes, err := os.ReadFile(filePath)
	if err != nil {
		slog.Error("error occur", err)
		return
	}
	err = json.Unmarshal(bytes, rawStruct)
	if err != nil {
		slog.Error("error occur", err)
		return
	}
	res = rawStruct.Options
	return
}
